0.96.0: special idents for the live blocks and events (Stage 3), keyed from bookings, entry-only, with Ring X and PPV overlays
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 1m55s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m29s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-03 23:07:01 +00:00
co-authored by Claude Opus 5.5
parent 1e02bc8971
commit ddba5796e7
45 changed files with 612 additions and 40 deletions
@@ -0,0 +1,157 @@
package tv.orbit.classic
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.tv.material3.Text
/** A block or event's own ident: 4 seconds, built from its channel's look (design/channels, Batches 1 to 4). */
internal const val BLOCK_IDENT_MS = 4_000L
/** What the app draws over a shared clip, so one film serves many nights or events. */
internal enum class BlockOverlay { None, RingXNight, TonightsEvent }
internal data class BlockIdent(val video: Int, val sting: Int, val overlay: BlockOverlay = BlockOverlay.None)
/** The approved, live presentations (Stage 3, 3 November 2026). Drive-In takeovers, themed nights and Premiere wait for their scheduling. */
internal val BlockIdents: Map<String, BlockIdent> = mapOf(
"riot.laughs" to BlockIdent(R.raw.block_riot_laughs, R.raw.block_riot_laughs_sting),
"riot.stunts" to BlockIdent(R.raw.block_riot_stunts, R.raw.block_riot_stunts_sting),
"riot.afterhours" to BlockIdent(R.raw.block_riot_afterhours, R.raw.block_riot_afterhours_sting),
"afterdark.bmovie" to BlockIdent(R.raw.block_afterdark_bmovie, R.raw.block_afterdark_bmovie_sting),
"afterdark.drivein" to BlockIdent(R.raw.block_afterdark_drivein, R.raw.block_afterdark_drivein_sting),
"afterdark.cult" to BlockIdent(R.raw.block_afterdark_cult, R.raw.block_afterdark_cult_sting),
"horror.slasher" to BlockIdent(R.raw.block_horror_slasher, R.raw.block_horror_slasher_sting),
"gold.sunday" to BlockIdent(R.raw.block_gold_sunday, R.raw.block_gold_sunday_sting),
"three.scottish" to BlockIdent(R.raw.block_three_scottish, R.raw.block_three_scottish_sting),
"vortex.movie" to BlockIdent(R.raw.block_vortex_movie, R.raw.block_vortex_movie_sting),
"orbit2.retro" to BlockIdent(R.raw.block_orbit2_retro, R.raw.block_orbit2_retro_sting),
"orbit2.spooky" to BlockIdent(R.raw.block_orbit2_spooky, R.raw.block_orbit2_spooky_sting),
"ringx.ppv" to BlockIdent(R.raw.block_ringx_ppv, R.raw.block_ringx_ppv_sting, BlockOverlay.TonightsEvent),
"terra.sunday" to BlockIdent(R.raw.block_terra_sunday, R.raw.block_terra_sunday_sting),
) + RingXNights.keys.associateWith { BlockIdent(R.raw.block_ringx_nights, R.raw.block_ringx_nights_sting, BlockOverlay.RingXNight) }
/** Orbit's own names for Ring X's weekly nights (approved 3 November 2026), and each night's rope colour. */
internal val RingXNights: Map<String, Pair<String, Long>> get() = mapOf(
"ringx.monday" to ("MONDAY NIGHT WARS" to 0xFFE81C30), "ringx.tuesday" to ("TUESDAY TITLE FIGHT" to 0xFFFFC21E),
"ringx.wednesday" to ("WEDNESDAY MAIN EVENT" to 0xFF38D8FF), "ringx.thursday" to ("THURSDAY THROWDOWN" to 0xFFA868FF),
"ringx.friday" to ("FRIDAY EXTREME" to 0xFFFF701A), "ringx.saturday" to ("SATURDAY WORLD TOUR" to 0xFF3AE07A))
/**
* The presentation for the changeover into [next], in order: a booked event or block entered here gets its own ident;
* anything else, including the second programme inside the same block, gets the channel's ident (null).
*/
internal fun blockIdentFor(current: SampleBroadcast, next: SampleBroadcast, enabled: Boolean): BlockIdent? =
if (!enabled || next.presentation.isEmpty() || next.presentation == current.presentation) null else BlockIdents[next.presentation]
/** A programme title made fit for a lower third: the guide's own clean title, or nothing if there isn't one. */
internal fun eventTitle(next: SampleBroadcast): String? = guideTitleParts(next.media.item.title).first.trim().takeIf { it.isNotEmpty() }
/** Drawn over a shared block clip, timed from the clip's own clock ([positionMs]) so it is complete well before the held last frame. */
@Composable
internal fun BlockOverlayLayer(ident: BlockIdent, next: SampleBroadcast, positionMs: () -> Long) {
var clock by remember { mutableLongStateOf(0L) }
LaunchedEffect(Unit) { while (true) { withFrameMillis { clock = positionMs() } } }
when (ident.overlay) {
BlockOverlay.None -> Unit
BlockOverlay.RingXNight -> RingXNightOverlay(next.presentation, clock)
BlockOverlay.TonightsEvent -> eventTitle(next)?.let { TonightLowerThird(it, clock) }
}
}
private fun ramp(t: Long, startMs: Long, lengthMs: Long) = ((t - startMs).toFloat() / lengthMs).coerceIn(0f, 1f)
private fun ease(u: Float) = u * u * (3 - 2 * u)
/** Ring X nights: the ropes light in the night's colour, bottom to top from 2.0 s, then its name wipes onto the apron from 2.3 s. Done by 2.7 s. */
@Composable
private fun RingXNightOverlay(key: String, t: Long) {
val (name, argb) = RingXNights[key] ?: return
val colour = Color(argb)
var box by remember { mutableStateOf(IntSize.Zero) }
// Positions are where the shared clip's camera settles (ring-x-nights-overlay.json), in its 1280x720 frame.
val ropes = listOf(listOf(289f to 363.6f, 640f to 367.1f, 991f to 363.6f), listOf(288.3f to 316.7f, 640f to 320.2f, 991.7f to 316.7f), listOf(287.6f to 269.7f, 640f to 273.2f, 992.4f to 269.7f))
val starts = listOf(2_000L, 2_120L, 2_240L)
Box(Modifier.fillMaxSize().onSizeChanged { box = it }) {
val sx = box.width / 1280f; val sy = box.height / 720f
Canvas(Modifier.fillMaxSize()) {
ropes.forEachIndexed { index, (a, mid, b) ->
val u = ease(ramp(t, starts[index], 300))
if (u <= 0f) return@forEachIndexed
val path = Path().apply {
moveTo(a.first * sx, a.second * sy)
// The rope's gentle sag, drawn as a curve through its middle point.
quadraticTo(mid.first * sx, (2 * mid.second - (a.second + b.second) / 2) * sy, b.first * sx, b.second * sy)
}
// Revealed left to right by clipping, so the curve itself never changes shape.
val right = (a.first + (b.first - a.first) * u) * sx
drawContext.canvas.save()
drawContext.canvas.clipRect(0f, 0f, right, size.height)
drawPath(path, colour.copy(alpha = .35f), style = Stroke(width = 14f * sx, cap = StrokeCap.Round))
drawPath(path, colour, style = Stroke(width = 5f * sx, cap = StrokeCap.Round))
drawPath(path, Color.White.copy(alpha = .65f), style = Stroke(width = 2f * sx, cap = StrokeCap.Round))
drawContext.canvas.restore()
}
}
val reveal = ease(ramp(t, 2_300, 400))
if (reveal > 0f && box.width > 0) {
val density = LocalDensity.current
val left = 263.3f * sx; val top = 436.5f * sy; val width = (1016.7f - 263.3f) * sx; val height = (508.7f - 436.5f) * sy
Box(Modifier.offset(with(density) { left.toDp() }, with(density) { top.toDp() })
.size(with(density) { width.toDp() }, with(density) { height.toDp() })
.clipToBounds()
.drawWithReveal(reveal)
.background(Color(0xE6100408))) {
Box(Modifier.fillMaxWidth().height(with(density) { (6f * sy).toDp() }).background(colour).align(Alignment.TopCenter))
Box(Modifier.fillMaxWidth().height(with(density) { (6f * sy).toDp() }).background(colour).align(Alignment.BottomCenter))
Text(name, Modifier.align(Alignment.Center).padding(horizontal = 12.dp), color = Color.White, fontSize = with(density) { (height * .5f).toSp() },
fontWeight = FontWeight.Bold, letterSpacing = 2.sp, maxLines = 1, overflow = TextOverflow.Clip, textAlign = TextAlign.Center)
}
}
}
}
/** Wipes a box in from the left: [u] from 0 (hidden) to 1 (all shown). */
private fun Modifier.drawWithReveal(u: Float) = this.then(Modifier.graphicsLayer {
clip = true
shape = object : androidx.compose.ui.graphics.Shape {
override fun createOutline(size: Size, layoutDirection: androidx.compose.ui.unit.LayoutDirection, density: androidx.compose.ui.unit.Density) =
androidx.compose.ui.graphics.Outline.Rectangle(androidx.compose.ui.geometry.Rect(Offset.Zero, Size(size.width * u, size.height)))
}
})
/** PPV Sunday's lower third: TONIGHT and the booked event's own title, from 2.7 s, settled by 3.05 s, before the hold. */
@Composable
private fun TonightLowerThird(title: String, t: Long) {
val u = ease(ramp(t, 2_700, 350))
if (u <= 0f) return
Box(Modifier.fillMaxSize()) {
Row(Modifier.align(Alignment.BottomStart).padding(start = 40.dp, bottom = 34.dp).fillMaxWidth(.62f)
.graphicsLayer { alpha = u; translationY = (1 - u) * 14f }.background(Navy.copy(alpha = .82f))) {
Box(Modifier.width(5.dp).height(64.dp).background(Color(0xFFE21E30)))
Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
Text("TONIGHT", color = Color(0xFFFFD278), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 3.sp)
// A long title wraps to a second line, then shrinks a little; it never runs off the screen.
Text(title, color = Color.White, fontSize = if (title.length > 34) 19.sp else 24.sp, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
}
}
@@ -40,8 +40,8 @@ private val Orbit2RetroAction = listOf("Knight Rider", "The A-Team", "Airwolf",
private val Orbit2Spooky = listOf("Goosebumps", "Are You Afraid of the Dark?", "Eerie, Indiana")
internal val Orbit2Shows get() = (Orbit2Daytime + Orbit2Teatime + Orbit2GameShows + Orbit2Panel + Orbit2RetroAction + Orbit2Spooky).distinct()
internal val Orbit2DayParts get() = listOf(
DayPart(17, 19, Orbit2Spooky, days = setOf(DayOfWeek.FRIDAY)),
DayPart(6, 15, Orbit2Daytime), DayPart(15, 18, Orbit2Teatime), DayPart(18, 21, Orbit2GameShows), DayPart(21, 0, Orbit2Panel), DayPart(0, 6, Orbit2RetroAction))
DayPart(17, 19, Orbit2Spooky, days = setOf(DayOfWeek.FRIDAY), key = "orbit2.spooky"),
DayPart(6, 15, Orbit2Daytime), DayPart(15, 18, Orbit2Teatime), DayPart(18, 21, Orbit2GameShows), DayPart(21, 0, Orbit2Panel), DayPart(0, 6, Orbit2RetroAction, key = "orbit2.retro"))
internal val Orbit2Mixed get() = Orbit2Shows.toSet()
/** Orbit Three, the cult comedy channel: alternative British comedy in the spirit of early BBC Three, and Scottish comedy at its heart. */
@@ -55,7 +55,7 @@ private val ThreeLate = listOf("Little Britain", "The League of Gentlemen", "Nig
private val ThreeOvernight = listOf("Two Pints of Lager and a Packet of Crisps", "The Inbetweeners", "Gavin & Stacey", "The Mighty Boosh", "Still Game", "Limmy's Show!", "Burnistoun", "Black Books")
internal val ThreeShows get() = (ThreeDaytime + ThreeEvening + ThreeLate).distinct()
internal val ThreeDayParts get() = listOf(
DayPart(21, 0, ThreeScottish, days = setOf(DayOfWeek.FRIDAY, DayOfWeek.SATURDAY)),
DayPart(21, 0, ThreeScottish, days = setOf(DayOfWeek.FRIDAY, DayOfWeek.SATURDAY), key = "three.scottish"),
DayPart(6, 18, ThreeDaytime), DayPart(18, 22, ThreeEvening), DayPart(22, 2, ThreeLate), DayPart(2, 6, ThreeOvernight))
/** Story sitcoms in order, sketch and standalone comedy mixed. */
private val ThreeInOrder = setOf("Gavin & Stacey", "Spaced", "Fresh Meat", "Phoenix Nights", "Being Human", "Green Wing", "This Country", "Extras", "The Office (UK)",
@@ -73,7 +73,7 @@ private val GoldOvernight = listOf("Only Fools and Horses", "Dad's Army", "Fathe
private val GoldSaturday = listOf("The Two Ronnies", "Minder", "Lovejoy")
internal val GoldShows get() = (GoldDaytime + GoldEvening + GoldLate + GoldSaturday).distinct()
internal val GoldDayParts get() = listOf(
DayPart(18, 22, listOf("Only Fools and Horses"), days = setOf(DayOfWeek.SUNDAY)),
DayPart(18, 22, listOf("Only Fools and Horses"), days = setOf(DayOfWeek.SUNDAY), key = "gold.sunday"),
DayPart(17, 19, GoldSaturday, days = setOf(DayOfWeek.SATURDAY)),
DayPart(6, 17, GoldDaytime), DayPart(17, 22, GoldEvening), DayPart(22, 2, GoldLate), DayPart(2, 6, GoldOvernight))
/** Only Fools and Horses runs in order, so Sunday Gold tells its story. Blackadder too. */
@@ -91,8 +91,8 @@ private val RiotGraveyard = listOf("Aqua Teen Hunger Force", "Sealab 2021", "Har
private val RiotStunts = listOf("Jackass", "Dirty Sanchez", "Bo' Selecta!")
internal val RiotShows get() = (RiotDaytime + RiotLaughs + RiotAfterHours + RiotGraveyard + RiotStunts).distinct()
internal val RiotDayParts get() = listOf(
DayPart(22, 0, RiotStunts, days = setOf(DayOfWeek.SATURDAY)),
DayPart(6, 18, RiotDaytime), DayPart(18, 21, RiotLaughs), DayPart(21, 2, RiotAfterHours), DayPart(2, 6, RiotGraveyard))
DayPart(22, 0, RiotStunts, days = setOf(DayOfWeek.SATURDAY), key = "riot.stunts"),
DayPart(6, 18, RiotDaytime), DayPart(18, 21, RiotLaughs, key = "riot.laughs"), DayPart(21, 2, RiotAfterHours, key = "riot.afterhours"), DayPart(2, 6, RiotGraveyard))
internal val RiotMixed get() = RiotShows.toSet() - setOf("Arrested Development", "BoJack Horseman")
private val Weekdays = setOf(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY)
@@ -123,7 +123,7 @@ internal val VortexShows get() = (VortexCartoons + VortexAnime + "Pokémon").dis
* Daytime suggestions not yet placed by hand go late, never into the daytime. Evening suggestions keep their evening.
*/
internal val VortexDayParts get() = listOf(
DayPart(20, 22, group = "movie", days = setOf(DayOfWeek.FRIDAY, DayOfWeek.SATURDAY)),
DayPart(20, 22, group = "movie", days = setOf(DayOfWeek.FRIDAY, DayOfWeek.SATURDAY), key = "vortex.movie"),
// Mornings are the staples. Reviewed modern anime joins in the afternoon, so it complements the channel rather than leading it.
DayPart(6, 12, VortexCartoons + VortexFavourites + listOf("Cardcaptor Sakura", "Cardcaptors", "Sailor Moon", "Dragon Ball", "Zoids: Chaotic Century", "Zoids")),
DayPart(12, 16, VortexCartoons + VortexFavourites + VortexFamilyAnime + listOf("Dragon Ball Z", "Mobile Suit Gundam Wing", "Tenchi Muyo! Ryo-Ohki", "Yu Yu Hakusho", "Outlaw Star", "The Big O")),
@@ -200,7 +200,7 @@ private val TerraWider = listOf("Hostile Planet", "Wild China", "Wild Russia", "
private val TerraEarlierNames = listOf("Our Planet II", "Dynasties", "Dynasties II", "Africa", "South Pacific", "Great Barrier Reef")
internal val TerraShows get() = (TerraLandmarks + TerraWider + TerraEarlierNames).distinct()
internal val TerraDayParts get() = listOf(
DayPart(20, 22, TerraLandmarks, days = setOf(DayOfWeek.SUNDAY)),
DayPart(20, 22, TerraLandmarks, days = setOf(DayOfWeek.SUNDAY), key = "terra.sunday"),
DayPart(6, 18, TerraShows), DayPart(18, 23, TerraLandmarks), DayPart(23, 6, TerraShows))
/** Wild: people meeting nature and surviving it. The presenters and participants are the story. */
@@ -285,14 +285,14 @@ internal val CultClassics = listOf("The Rocky Horror Picture Show", "Repo Man",
* and the last film it starts runs to its natural end. When every film in it is resting, the one that has waited longest
* plays, as on any film channel; when none of its films are in the library at all, the channel's usual block carries on.
*/
internal val HorrorDayParts get() = listOf(DayPart(20, 2, SlasherSaturday, days = setOf(DayOfWeek.SATURDAY)))
internal val HorrorDayParts get() = listOf(DayPart(20, 2, SlasherSaturday, days = setOf(DayOfWeek.SATURDAY), key = "horror.slasher"))
/**
* After Dark's Saturday staple: one whole hosted episode, in order, running its full length however long. Its window opens at 20:00
* because the film before it is usually still running: starting from the first slot after 20:00 lands it around 21:00.
*/
internal const val LAST_DRIVE_IN = "The Last Drive-in with Joe Bob Briggs"
internal val AfterDarkEvents get() = listOf(DayPart(21, 1, BMovieThrowbacks, days = setOf(DayOfWeek.FRIDAY)), DayPart(20, 1, listOf(LAST_DRIVE_IN), days = setOf(DayOfWeek.SATURDAY)),
DayPart(21, 1, CultClassics, days = setOf(DayOfWeek.SUNDAY)))
internal val AfterDarkEvents get() = listOf(DayPart(21, 1, BMovieThrowbacks, days = setOf(DayOfWeek.FRIDAY), key = "afterdark.bmovie"), DayPart(20, 1, listOf(LAST_DRIVE_IN), days = setOf(DayOfWeek.SATURDAY), key = "afterdark.drivein"),
DayPart(21, 1, CultClassics, days = setOf(DayOfWeek.SUNDAY), key = "afterdark.cult"))
/** Orbit Junior: British children's TV for about 5 to 11, with the classics at breakfast. Tots is the preferred home of modern preschool. */
private val JuniorBreakfast = listOf("Thomas the Tank Engine & Friends", "Thomas & Friends", "Postman Pat", "Brum", "Rosie and Jim", "Pingu", "Pingu in the City", "Button Moon",
@@ -331,11 +331,11 @@ private val RingXLate = listOf("Dark Side of the Ring", "The Monday Night War",
"Who Killed WCW?", "The Wrestlers", "Wrestlers", "WWE Legends House", "WWE NXT")
internal val RingXShows get() = (RingXMonday + RingXTuesday + RingXWednesday + RingXThursday + RingXFriday + RingXSaturday + RingXDaytimeVault + RingXLate + RingXVault).distinct()
internal val RingXDayParts get() = listOf(
DayPart(18, 23, RingXMonday, days = setOf(DayOfWeek.MONDAY)), DayPart(18, 23, RingXTuesday, days = setOf(DayOfWeek.TUESDAY)),
DayPart(18, 23, RingXWednesday, days = setOf(DayOfWeek.WEDNESDAY)), DayPart(18, 23, RingXThursday, days = setOf(DayOfWeek.THURSDAY)),
DayPart(18, 23, RingXFriday, days = setOf(DayOfWeek.FRIDAY)), DayPart(18, 23, RingXSaturday, days = setOf(DayOfWeek.SATURDAY)),
DayPart(18, 23, RingXMonday, days = setOf(DayOfWeek.MONDAY), key = "ringx.monday"), DayPart(18, 23, RingXTuesday, days = setOf(DayOfWeek.TUESDAY), key = "ringx.tuesday"),
DayPart(18, 23, RingXWednesday, days = setOf(DayOfWeek.WEDNESDAY), key = "ringx.wednesday"), DayPart(18, 23, RingXThursday, days = setOf(DayOfWeek.THURSDAY), key = "ringx.thursday"),
DayPart(18, 23, RingXFriday, days = setOf(DayOfWeek.FRIDAY), key = "ringx.friday"), DayPart(18, 23, RingXSaturday, days = setOf(DayOfWeek.SATURDAY), key = "ringx.saturday"),
// PPV Sunday: one event, starting near 19:00 and running to its natural end, however late.
DayPart(19, 20, PpvSunday, days = setOf(DayOfWeek.SUNDAY), onTime = true, once = true),
DayPart(19, 20, PpvSunday, days = setOf(DayOfWeek.SUNDAY), onTime = true, once = true, key = "ringx.ppv"),
DayPart(6, 23, RingXDaytimeVault), DayPart(23, 6, RingXLate))
/**
@@ -7,7 +7,9 @@ internal data class DayPart(val fromHour: Int, val toHour: Int, val titles: List
/** An appointment: the programmes before it are chosen, where one fits, to finish by its hour, so it starts on time. */
val onTime: Boolean = false,
/** One start a night: once a programme from this event has started, the rest of its window goes to the usual block. */
val once: Boolean = false) {
val once: Boolean = false,
/** The block's or event's presentation, such as "riot.laughs": its own ident on entering it. Empty for ordinary blocks. */
val key: String = "") {
fun covers(hour: Int) = if (fromHour <= toHour) hour in fromHour until toHour else hour >= fromHour || hour < toHour
/** An event that runs past midnight belongs to the night it started, so its small hours count from the day before. */
fun covers(hour: Int, day: java.time.DayOfWeek) = covers(hour) && (days.isEmpty() || (if (fromHour > toHour && hour < toHour) day.minus(1) else day) in days)
@@ -136,7 +138,9 @@ internal data class ScheduleCursor(val lastSeriesId: String? = null, val marks:
internal data class ScheduleEntry(val seriesId: String, val mark: EpisodeMark, val media: ScheduledMedia, val startMs: Long,
/** Why the planner chose this, for diagnostics only. Empty for programmes planned before reasons were kept. */
val why: String = "") {
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 endMs get() = startMs + media.durationMs
}
@@ -249,13 +253,13 @@ internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor,
var start = fromMs
val marks = cursor.marks.toMutableMap()
while (start < untilMs) {
val (available, block) = dayPartChoice(pool, dayParts, start, zone)
val (available, block, part) = dayPartFor(pool, dayParts, start, zone)
// An event naming only a series plays its next whole episode, once a night. Everywhere else is films only.
val series = available.singleOrNull()?.takeIf { !it.isFilm && block.startsWith("event ") }
if (series != null && shown[series.id]?.let { start - it < SERIES_NIGHT_MS } != true) {
val episode = nextEpisode(series, marks[series.id])
entries += ScheduleEntry(series.id, episode.mark, ScheduledMedia(scheduledItem(series.title, episode), episode.sourceId, episode.durationMs), start,
"$block; next episode in order, played whole")
"$block; next episode in order, played whole", part?.key.orEmpty())
marks[series.id] = episode.mark
shown[series.id] = start
last = series.id
@@ -266,7 +270,8 @@ internal fun extendFilmSchedule(pool: List<PoolSeries>, cursor: ScheduleCursor,
val (film, why) = chooseFilm(films, shown, start, restMs, avoid)
val copy = film.episodes.first()
val item = SampleItem(film.title, "Movie", copy.durationMs / 60_000, "", copy.id, copy.durationMs)
entries += ScheduleEntry(film.id, copy.mark, ScheduledMedia(item, copy.sourceId, copy.durationMs), start, "$block; $why")
// Only a programme actually drawn from the event's own titles carries its presentation.
entries += ScheduleEntry(film.id, copy.mark, ScheduledMedia(item, copy.sourceId, copy.durationMs), start, "$block; $why", if (film in available) part?.key.orEmpty() else "")
shown[film.id] = start
last = film.id
start += copy.durationMs
@@ -394,7 +399,7 @@ 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)
entries += ScheduleEntry(series.id, episode.mark, media, start, why, if (series in available) part?.key.orEmpty() else "")
marks[series.id] = episode.mark
run = if (series.id == last) run + 1 else 1
last = series.id
@@ -443,6 +448,8 @@ internal fun topUpPlan(existing: ChannelPlan?, aired: ScheduleCursor, pool: List
*/
internal class ScheduledChannel(val loop: SampleChannel, plan: ChannelPlan) : SampleChannel(loop.lineup, loop.name, loop.number) {
@Volatile var plan: ChannelPlan = plan
private val parts by lazy { SmartChannels.firstOrNull { it.number == number }?.dayParts.orEmpty() }
private fun presented(entry: ScheduleEntry) = SampleBroadcast(entry.media, entry.startMs, presentationOf(entry, parts))
/** Runs over the plan for a while, as Wind Down Now does, leaving the plan itself as it was. */
@Volatile var stepIn: ChannelPlan? = null
fun seriesIdAt(startMs: Long) = (stepIn?.entries.orEmpty() + plan.entries).firstOrNull { it.startMs == startMs }?.seriesId
@@ -457,7 +464,7 @@ internal class ScheduledChannel(val loop: SampleChannel, plan: ChannelPlan) : Sa
when {
timeMs < entry.startMs -> high = middle - 1
timeMs >= entry.endMs -> low = middle + 1
else -> return SampleBroadcast(entry.media, entry.startMs)
else -> return presented(entry)
}
}
// Between plans the loop fills in, cut short so it never runs over the next planned programme.
@@ -467,3 +474,22 @@ internal class ScheduledChannel(val loop: SampleChannel, plan: ChannelPlan) : Sa
return fill.copy(media = fill.media.copy(durationMs = next.startMs - fill.startMs))
}
}
internal val PRESENTATION_KEY = Regex("[a-z0-9]{1,20}\\.[a-z0-9]{1,20}")
/**
* A booked programme's presentation: the key saved with it when it was booked. A programme booked before keys were kept
* gets one only when its recorded reason names exactly one keyed block or event that covers its start; anything less
* certain, or no reason at all, gives none, and the ordinary channel ident plays. Nothing is worked out from the clock alone.
*/
internal fun presentationOf(entry: ScheduleEntry, parts: List<DayPart>, zone: java.time.ZoneId = java.time.ZoneId.systemDefault()): String {
if (entry.presentation.isNotEmpty()) return entry.presentation
val recorded = entry.why.substringBefore(';').trim()
if (recorded.isEmpty()) return ""
val local = java.time.Instant.ofEpochMilli(entry.startMs).atZone(zone)
val matches = parts.filter { part ->
part.key.isNotEmpty() && part.covers(local.hour, local.dayOfWeek) &&
recorded == (if (part.days.isNotEmpty()) "event " else "block ") + part.group.ifEmpty { "${part.fromHour}-${part.toHour}" }
}
return matches.singleOrNull()?.key.orEmpty()
}
@@ -66,7 +66,7 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
connection.connectTimeout = 10_000
connection.readTimeout = request.readTimeoutMs ?: if (request.path == "/Sessions/Logout") 5_000 else 15_000
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.95.7\"")
connection.setRequestProperty("X-Emby-Authorization", "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.96.0\"")
request.token?.let { connection.setRequestProperty("X-Emby-Token", it) }
if (request.method == "POST") {
val bytes = request.body.orEmpty().toByteArray(Charsets.UTF_8)
@@ -90,35 +90,47 @@ internal fun loadNextPlayer(context: Context, session: EmbySampleSession, plan:
@Composable
internal fun IdentOverlay(session: EmbySampleSession, channel: SampleChannel, next: SampleBroadcast, identMs: Long, startedLateMs: Long,
/** Filling time after a programme ended early: says when the next one starts, and keeps to a still picture if idents are off. */
early: Boolean = false) {
early: Boolean = false,
/** Entering a block or event with its own ident: that film instead of the channel's, with anything drawn over it. */
block: BlockIdent? = null) {
val context = LocalContext.current
val mood = if (channel.number == TOTS_NUMBER) totsMood(next.startMs) else null
val settings = remember { OrbitSettings(context) }
val fade = remember { Animatable(0f) }
LaunchedEffect(Unit) { fade.animateTo(1f, tween(mood?.fadeMs ?: 400)) }
Box(Modifier.fillMaxSize().graphicsLayer { alpha = fade.value }.background(Navy)) {
val video = identVideo(channel.number, next.startMs)
val video = block?.video ?: identVideo(channel.number, next.startMs)
// With idents off, Tots still says goodbye with a picture that doesn't move.
if (mood != null && !settings.idents) Image(painterResource(mood.still), null, Modifier.fillMaxSize())
else if (video != null && !(early && !settings.idents)) {
val player = remember(video) {
ExoPlayer.Builder(context).build().apply {
setMediaItem(MediaItem.fromUri(RawResourceDataSource.buildRawResourceUri(video)))
// A block's sting is a separate quiet file, only joined to the picture when Block ident sound is on.
val sound = block?.takeIf { settings.blockIdentSound }?.sting
if (sound == null) setMediaItem(MediaItem.fromUri(RawResourceDataSource.buildRawResourceUri(video)))
else {
val raw = androidx.media3.exoplayer.source.ProgressiveMediaSource.Factory(androidx.media3.datasource.DefaultDataSource.Factory(context))
setMediaSource(androidx.media3.exoplayer.source.MergingMediaSource(raw.createMediaSource(MediaItem.fromUri(RawResourceDataSource.buildRawResourceUri(video))),
raw.createMediaSource(MediaItem.fromUri(RawResourceDataSource.buildRawResourceUri(sound)))))
}
seekTo(startedLateMs.coerceIn(0, identMs))
volume = if (mood != null && settings.identSound && TotsJingle.take(mood, System.currentTimeMillis())) 1f else 0f
volume = if (block != null) (if (settings.blockIdentSound) 1f else 0f)
else if (mood != null && settings.identSound && TotsJingle.take(mood, System.currentTimeMillis())) 1f else 0f
prepare(); playWhenReady = true
}
}
DisposableEffect(player) { onDispose { player.release() } }
// Its own surface, faded with the overlay, sitting over the show's own picture.
AndroidView(modifier = Modifier.fillMaxSize(), factory = { overlaySurface(it, player) }, update = { it.alpha = fade.value })
if (block != null) BlockOverlayLayer(block, next) { player.currentPosition }
} else {
ProgrammeArtwork(session, channel, next)
ChannelBrands.forNumber(channel.number)?.let { brand ->
Image(painterResource(brand.logo), brand.displayName, Modifier.align(Alignment.Center).width(400.dp).height(125.dp))
}
}
Column(Modifier.align(Alignment.BottomStart).padding(start = 40.dp, bottom = 32.dp).background(Navy.copy(alpha = .72f)).padding(horizontal = 14.dp, vertical = 8.dp)) {
// A booked event's own lower third says what's next instead.
if (block?.overlay != BlockOverlay.TonightsEvent || eventTitle(next) == null) Column(Modifier.align(Alignment.BottomStart).padding(start = 40.dp, bottom = 32.dp).background(Navy.copy(alpha = .72f)).padding(horizontal = 14.dp, vertical = 8.dp)) {
Text(if (early) "NEXT AT ${clock(next.startMs)}" else "NEXT", color = Color(0xFFD5DCEA), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp)
Text(guideTitleParts(next.media.item.title).first, color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
@@ -1,7 +1,9 @@
package tv.orbit.classic
internal data class ScheduledMedia(val item: SampleItem, val sourceId: String, val durationMs: Long)
internal data class SampleBroadcast(val media: ScheduledMedia, val startMs: Long) {
internal data class SampleBroadcast(val media: ScheduledMedia, val startMs: Long,
/** The booked programme's block or event presentation key (see [presentationOf]), empty for ordinary programmes. */
val presentation: String = "") {
val endMs: Long get() = startMs + media.durationMs
fun offsetAt(timeMs: Long) = (timeMs - startMs).coerceIn(0, media.durationMs - 1)
}
@@ -55,8 +55,11 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC
else { stream?.discard(session); null }
}
val next = shows[1]
val identMs = identLength(channel.number, next.startMs)
val identsOn = remember { OrbitSettings(settingsContext).idents }
val specialOn = remember { OrbitSettings(settingsContext).specialIdents }
// Entering a booked block or event with its own ident; otherwise (and inside a block) the channel's ident.
val block = if (identsOn) blockIdentFor(current, next, specialOn) else null
val identMs = if (block != null) BLOCK_IDENT_MS else identLength(channel.number, next.startMs)
val identsHere = channel is ScheduledChannel && clockOffsetMs == 0L && channel.number != DRIVE_IN_NUMBER && next.startMs == current.endMs && (identsOn || channel.number == TOTS_NUMBER)
val phase = if (identsHere) identPhase(current.startMs, current.endMs, now, identMs) else IdentPhase.None
// Each changeover in the playback notes, so a missing ident can be explained afterwards.
@@ -72,7 +75,7 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC
var playing by remember(channel) { mutableStateOf<LoadedNext?>(null) }
DisposableEffect(channel) { onDispose { loaded?.discard(session) } }
LaunchedEffect(channel, current.startMs, phase == IdentPhase.Showing) {
if (phase == IdentPhase.Showing) PlaybackNotes.add(notes, "channel=${channel.number} ident shown next=${next.startMs} loaded=${loaded?.startMs == next.startMs}")
if (phase == IdentPhase.Showing) PlaybackNotes.add(notes, "channel=${channel.number} ident shown next=${next.startMs} loaded=${loaded?.startMs == next.startMs}" + if (block != null) " block=${next.presentation}" else "")
}
// A problem here only means the next show tunes in the ordinary way.
LaunchedEffect(channel, current.startMs, phase == IdentPhase.None) {
@@ -117,7 +120,9 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC
val plan = loadedNow?.plan ?: prepared?.takeIf { it.item.id == current.media.item.id && preparedSlot == current.startMs && problem == null }
// The ident playing out, held on its last frame until the next programme's first picture is on screen.
var heldIdent by remember(channel) { mutableStateOf<SampleBroadcast?>(null) }
LaunchedEffect(phase == IdentPhase.Showing, next.startMs) { if (phase == IdentPhase.Showing) heldIdent = next }
// The block's ident chosen at the changeover, kept with the held ident so its length and overlay stay the same throughout.
var heldBlock by remember(channel) { mutableStateOf<BlockIdent?>(null) }
LaunchedEffect(phase == IdentPhase.Showing, next.startMs) { if (phase == IdentPhase.Showing) { heldBlock = block; heldIdent = next } }
// A file can stop before its slot ends, when Emby lists it longer than it really runs (a Tots Night Garden on
// 3 November stopped 3 minutes early). Instead of a black screen, the channel's ident plays and holds its last
// frame, saying what's next and when, until the next programme's booked start. The schedule itself doesn't move.
@@ -148,7 +153,7 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC
if (channel is ScheduledChannel && next.startMs == current.endMs && finishedEarly(at, current.endMs) && heldIdent == null) {
PlaybackNotes.add(notes, "channel=${channel.number} endedEarlyMs=${current.endMs - at} item=${current.media.item.id}")
android.util.Log.w("OrbitSchedule", "channel=${channel.number} endedEarlyMs=${current.endMs - at} item=${current.media.item.id}")
endedEarly = next.startMs; heldIdent = next
endedEarly = next.startMs; heldBlock = null; heldIdent = next
}
})
} else {
@@ -169,10 +174,11 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC
}
heldIdent?.let { held ->
key(held.startMs) {
val length = identLength(channel.number, held.startMs)
val early = endedEarly == held.startMs
val heldAs = if (early) null else heldBlock
val length = if (heldAs != null) BLOCK_IDENT_MS else identLength(channel.number, held.startMs)
val startedLate = remember { if (early) 0L else (System.currentTimeMillis() + clockOffsetMs - (held.startMs - length)).coerceAtLeast(0) }
IdentOverlay(session, channel, held, length, startedLate, early)
IdentOverlay(session, channel, held, length, startedLate, early, heldAs)
}
}
introPlayback?.let { IntroOverlay(it) }
@@ -94,7 +94,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) }) }
.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) }) }
write(file("schedule", number), root(userId, number).put("tail", encodeCursor(plan.tail)).put("entries", entries))
}
fun loadPlan(userId: String, number: Int): ChannelPlan? = read(file("schedule", number), userId, number) { root ->
@@ -104,7 +104,9 @@ internal class ScheduleStore(private val directory: File) {
val duration = validDuration(o.getLong("d"))
val mark = o.getJSONArray("n").let { EpisodeMark(it.getInt(0), it.getInt(1)) }
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))
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())
}
require(entries.zipWithNext().all { (first, second) -> first.endMs <= second.startMs })
ChannelPlan(entries, decodeCursor(root.getJSONObject("tail")))
@@ -33,7 +33,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B
next.instanceFollowRedirects = false
next.connectTimeout = 10_000
next.readTimeout = 20_000
next.setRequestProperty("User-Agent", "OrbitTV/0.95.7")
next.setRequestProperty("User-Agent", "OrbitTV/0.96.0")
next.setRequestProperty("Accept-Encoding", "identity")
session.mediaHeaders(address).forEach { (key, value) -> next.setRequestProperty(key, value) }
if (dataSpec.position != 0L || dataSpec.length != C.LENGTH_UNSET.toLong()) {
@@ -59,6 +59,14 @@ internal class OrbitSettings(context: Context) {
var driveInIntro: Boolean
get() = saved.getBoolean("drive_in_intro", true)
set(value) { saved.edit().putBoolean("drive_in_intro", value).apply() }
/** The approved block and event idents (Riot Laughs, PPV Sunday and the rest). Off: every changeover gets the channel's own ident. */
var specialIdents: Boolean
get() = saved.getBoolean("special_idents", true)
set(value) { saved.edit().putBoolean("special_idents", value).apply() }
/** Their short original stings. Off by default: block idents are silent unless chosen. */
var blockIdentSound: Boolean
get() = saved.getBoolean("block_ident_sound", false)
set(value) { saved.edit().putBoolean("block_ident_sound", value).apply() }
/** Turns off moving presentation such as the Drive-In's curtains. More screens will follow it as they gain motion. */
var reduceMotion: Boolean
get() = saved.getBoolean("reduce_motion", false)
@@ -148,6 +156,8 @@ private fun ViewingDetail(totsOn: Boolean, windingDown: Boolean, onWindDown: (Bo
var identSound by remember { mutableStateOf(settings.identSound) }
var driveInIntro by remember { mutableStateOf(settings.driveInIntro) }
var reduceMotion by remember { mutableStateOf(settings.reduceMotion) }
var specialIdents by remember { mutableStateOf(settings.specialIdents) }
var blockIdentSound by remember { mutableStateOf(settings.blockIdentSound) }
var confirming by remember { mutableStateOf(false) }
Column(modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
SettingLine("Subtitles", "Turn on English subtitles whenever you tune in, if the programme has them. You can still change them while watching, by pressing right.") {
@@ -162,6 +172,12 @@ private fun ViewingDetail(totsOn: Boolean, windingDown: Boolean, onWindDown: (Bo
SettingLine("Ident sound", "Let Tots play its jingle, at most once every 30 minutes.") {
OrbitButton(if (identSound) "On" else "Off", Modifier.width(64.dp), selected = identSound, onClick = { identSound = !identSound; settings.identSound = identSound })
}
SettingLine("Special idents", "Give named blocks and events their own ident as they begin, such as Riot Laughs or PPV Sunday. Off uses each channel's usual ident.") {
OrbitButton(if (specialIdents) "On" else "Off", Modifier.width(64.dp), selected = specialIdents, onClick = { specialIdents = !specialIdents; settings.specialIdents = specialIdents })
}
SettingLine("Special ident sound", "Play the short sound with each special ident. Off keeps them silent.") {
OrbitButton(if (blockIdentSound) "On" else "Off", Modifier.width(64.dp), selected = blockIdentSound, onClick = { blockIdentSound = !blockIdentSound; settings.blockIdentSound = blockIdentSound })
}
SettingLine("Drive-In curtains", "Play the curtain intro, with its fanfare, as you go into a screening. Back skips it.") {
OrbitButton(if (driveInIntro) "On" else "Off", Modifier.width(64.dp), selected = driveInIntro, onClick = { driveInIntro = !driveInIntro; settings.driveInIntro = driveInIntro })
}